/** 
 * 项目名称:Sprider-WebMagic 
 * 文件名称:QQTVScorePageProcessor.java 
 * 包名:com.xiaotu.spider.qq.pageprocessor 
 * 创建日期:2020年3月23日下午1:54:32 
 * Copyright (c) 2020, zxaiye1314@163.com All Rights Reserved.</pre> 
 */  
package com.xiaotu.spider.iqy.pageprocessor;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xiaotu.common.model.TvScoreModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.GsonUtils;
import com.xiaotu.common.util.KeywordEncode;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.common.util.RegexUtils;
import com.xiaotu.common.util.TVProcessUtils;
import com.xiaotu.server.service.maoyan.MaoYanMovieBasicInfoService;
import com.xiaotu.spider.AUrlPageProcessor;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;

/** 
 * 项目名称：Sprider-WebMagic    
 * 类名称：IQYNetTvScorePageProcessor    
 * 类描述：爱奇艺网剧评分   
 * 创建人：张晓   
 * 创建时间：2020年3月23日 下午1:54:32    
 * @version   
 */
@Component("IQYNetTvScorePageProcessor")
public class IQYNetTvScorePageProcessor extends AUrlPageProcessor {

	@Autowired
	private MaoYanMovieBasicInfoService maoYanMovieBasicInfoService;
	
	private String start_url = "https://www.iqiyi.com/dianshiju/?vfrm=pcw_home&vfrmblk=C&vfrmrst=712211_channel_dianshiju";
	
	private String search_url = "https://so.iqiyi.com/so/q_%s?source=input";
	
	private String score_url = "https://pcw-api.iqiyi.com/video/score/getsnsscore?qipu_ids=%s&tvid=%s&pageNo=1";
	
	private String albumidRegex = "(?<=albumid=).*?(?=&c1=2)";
	
	@Override
	public void process(Page page) {
		Map<String, Object> tvMap = page.getRequest().getExtras();
        switch (this.getPageDataType(page))
        {
            case Constants.PageDataType.SEARCH_LIST:
                this.searchListProcess(page, tvMap);
                break;
            case Constants.PageDataType.URL:
                this.addRequsetProcess(page);
                break;
            case Constants.PageDataType.TV_RECORD:
            	this.scoreProcess(page,tvMap);
            	break;
            default:
                break;
        }
	}

	/** scoreProcess(获取评分)   
	 * 创建人：张晓   
	 * 创建时间：2020年3月25日 下午1:32:05    
	 * 修改备注： 
	 * @param page
	 * @param tvMap  
	 */
	private void scoreProcess(Page page, Map<String, Object> tvMap) {
		
		String rawText = page.getRawText();
		JSONObject fromJson = GsonUtils.fromJson(rawText, JSONObject.class);
		JSONArray dataArray = (JSONArray)fromJson.get("data");
		String score = dataArray.getJSONObject(0).getString("sns_score");
		page.putField(TvScoreModel.class.getName(), new TvScoreModel(
				tvMap.get("tvname").toString(),
				tvMap.get("dataid").toString(),
				score,
				Constants.SiteName.IQIYI
				));
	}

	/** searchListProcess(匹配剧)   
	 * 创建人：张晓   
	 * 创建时间：2020年3月23日 下午2:07:49    
	 * 修改备注： 
	 * @param page
	 * @param tvMap  
	 */
	private void searchListProcess(Page page, Map<String, Object> tvMap) {
		Html html = page.getHtml();
		List<String> divList = html.xpath("//div[@desc='card']").all();
		for(String div : divList){
			Html divHtml = new Html(div);
			//播放平台
			String siteName = divHtml.xpath("//span[@class='play-source']"
					+ "//em[@class='player-name']//text()").get();
			if(Constants.SiteName.IQIYI.equals(siteName)){
				
				String tvname = divHtml.xpath("//div[@class='result-right']"
						+ "//h3[@class='qy-search-result-tit']//a[@class='main-tit']/@title").get();
				
				String tvtype = divHtml.xpath("//div[@class='result-right']"
						+ "//h3[@class='qy-search-result-tit']//span[@class='item-type']//text()").get();
				
				List<String> actors = divHtml.xpath("//div[@desc='主演']//a[@class='info-link']/@title").all();
				List<String> directors = divHtml.xpath("//div[@desc='导演']//a[@class='info-link']/@title").all();
				
				String albumId = RegexUtils.regexesSearch(divHtml.xpath("//div[@desc='card']/@data-searchpingback-position").get(), albumidRegex);
				
				if(TVProcessUtils.tvMatched(tvMap,tvname,tvtype,actors,directors)){
					PageUtils.addTargetRequest(page, String.format(score_url, albumId, albumId), tvMap);
					break;
				}
			}
		}
		
	}

	/** addRequsetProcess(添加请求)   
	 * 创建人：张晓   
	 * 创建时间：2020年3月23日 下午2:07:46    
	 * 修改备注： 
	 * @param page
	 * @param tvMap  
	 */
	private void addRequsetProcess(Page page) {
		List<Map<String,Object>> list = maoYanMovieBasicInfoService.getNetTvInfoList(Constants.SiteName.IQIYI);
		for(Map<String,Object> map : list){
			map.put("tvName", map.get("tvname").toString());
			map.put("tvType", map.get("tvtype").toString());
			PageUtils.addTargetRequest(page, String.format(search_url, KeywordEncode.encode(map.get("tvname").toString())), map);
		}
	}

	@Override
	protected String[] getStartRequestUrls() {
		return new String[]{start_url};
	}

	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.TV_IQIYI;
	}

	@Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
        if (url.contains("/so/q_")){
            return Constants.PageDataType.SEARCH_LIST;
        }
        else if (url.contains("/dianshiju")){
            return Constants.PageDataType.URL;
        }
        else if (url.contains("/video/score")){
            return Constants.PageDataType.TV_RECORD;
        }
        return Constants.PageDataType.UNKNOW;
	}
	
}
